package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	. "web_api_gin/controller"
	"web_api_gin/core"
	"web_api_gin/dao"
	"web_api_gin/dto"
	"web_api_gin/entity"
	"web_api_gin/service"
)

//后台登录控制器
var LoginApi = LoginController{}

type LoginController struct {
}

// 账号登录
func (c *LoginController) Account(ctx *gin.Context) {
	var (
		form    dto.SysUsersApiSignReq
		sysUser *entity.SysUsers
		token   interface{}
	)
	if err := ctx.ShouldBind(&form); err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, core.ValidatorTranslateError(err))
		return
	}
	//设置表单数据，方便保存日志
	ctx.Set("formData", form)
	//调用登录方法并获取用户数据
	sysUser, err := service.SysUser.Login(ctx, form)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, err.Error())
		return
	}
	token, err = service.SysUser.TokenCreate(ctx, sysUser, nil)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, err.Error())
		return
	}
	//设置用户信息
	ctx.Set("userData", sysUser)
	//刷新用户角色缓存
	dao.SysRole.GetUserRoleListCache(ctx, sysUser, true)
	//刷新用户权限缓存
	userRoleList, userPermList, _ := service.SysUser.GetAdminUserConf(ctx, sysUser, true)
	Success(ctx, gin.H{
		"token":    token,
		"userData": sysUser,
		"roleList": userRoleList,
		"permList": userPermList,
	})
}

//退出登录接口
func (c *LoginController) Logout(ctx *gin.Context) {
	userData, userToken, err := service.SysUser.AuthorizationGetUserData(ctx)
	if err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, err.Error())
		return
	}
	if userData == nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, "用户不存在")
		return
	}
	if _, err := service.SysUser.TokenDelete(ctx, userToken); err != nil {
		ErrorWithMessage(ctx, http.StatusExpectationFailed, "注销失败:"+err.Error())
	}
	Success(ctx, gin.H{})
}
